<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;
/**
 *
 */
class Mautic extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $connection = '';
    protected $model = null;
    protected $PRIVATE_API_KEY = null;

    public function _initialize()
    {
        $this->PRIVATE_API_KEY = '78c1f81407961e4188d25c9935b98777-5e7fba0f-faae7227';
        $this->connection = Config::get('mautic');
        parent::_initialize();
    }

    public function Mailgun()
    {
        $Mailgun_id = 'sandbox8402c6df0b6e4967a9ea1e84e4f05c7d.mailgun.org';
        $to = '2684038581@qq.com';
        $subject = 'Hello';
        $text = 'Testing some Mailgun awesomness!';

        $url = 'https://api.mailgun.net/v3/'.$Mailgun_id.'/messages';
        $data = array(
            'from'    => "mailgun@".$Mailgun_id.".com",
            'to'      => $to,
            'subject' => $subject,
            'text'    => $text
        );
        $return = $this->posturlMailgun($url,$data);
        dump($return);die;
    }

    public function posturlMailgun($url,$data = array()){
        $headerArray = array('Authorization:Basic '.base64_encode("api:".$this->PRIVATE_API_KEY));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //http://zh.dnssystem.cn/api/Mautic/accounturl_iscustom?type=2&accounturl=56
    public function accounturl_iscustom()
    {
        $type = $this->request->request('type');
        $where = array();
        $where['status'] = 'normal';
        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        }else{
            //从56店铺开始更新
            $where['id']  = array('egt',56);
        }
        $result = array();
        if(!empty($type)){
            $iscustom = table('fedition_accounturl')
                ->where('iscustom',1)
                ->where($where)
                ->order('updatetime_mautic asc')
                ->find();
            if($iscustom){
//                foreach ($iscustom as $k => $v) {
                    $result = $this->MauticShopify($iscustom,$type);
//                }
                $accounturlarr['updatetime_mautic'] = time();
                table('fedition_accounturl')
                    ->where('id',$iscustom['id'])
                    ->update($accounturlarr);
            }
        }
        $this->success('操作成功',$result);
    }

    public function MauticShopify($iscustom,$type)
    {
        date_default_timezone_set('Asia/Shanghai');
        $url = $iscustom['shopifyname']."/admin/api/2021-07/customers.json";
        //获取之前所有的
        if($type == 2){
            $limit = '150';
            $before_leads= table('leads')
                ->where('accounturl',$iscustom['id'])
                ->order('ycreated_at asc')
                ->find();
            if($before_leads){
                $created_at_max = $before_leads['ycreated_at'];
                if (empty($created_at_max)) {
                    date_default_timezone_set('Asia/Shanghai');
                    $created_at_max1 = date('Y-m-d', strtotime("now"));
                    $created_at_max2 = date('H:i:s', strtotime("now"));
                    $created_at_max = $created_at_max1.'T'.$created_at_max2.'-04:00';
                }else{
                    $created_at_maxs = explode('T',$created_at_max);
                    $created_at_maxs2 = explode('+',$created_at_maxs[1]);
                    $created_at_maxs3 = strtotime($created_at_maxs[0].' '.$created_at_maxs2[0]) - 8*3600;
                    $created_at_max = date('Y-m-d\TH:i:s',$created_at_maxs3).'+08:00';
                }
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1.'T'.$created_at_max2.'-04:00';
            }
            //拉取之前的订单
            $url = $url.'?created_at_max='.$created_at_max;
        }
        //实时更新
        if($type == 1){
            $limit = '50';
            $last_leads = table('leads')
                ->where('accounturl',$iscustom['id'])
                ->order('ycreated_at desc')
                ->find();
            if($last_leads){
                $updated_at_min = $last_leads['ycreated_at'];
                if (!empty($updated_at_min)) {
                    $updated_at_mins = explode('T',$updated_at_min);
//                    $updated_at_mins2 = explode('+',$$updated_at_mins[1]);
//                    $updated_at_mins3 = strtotime($updated_at_mins[0].' '.$updated_at_mins2[0]) - 8*3600;
//                    $updated_at_min = date('Y-m-d\TH:i:s',$updated_at_mins3).'+08:00';
                    $updated_at_mins[0] = date('Y-m-d',strtotime("$updated_at_mins[0]-1day"));
                    $updated_at_min = $updated_at_mins[0] .'T'.$updated_at_mins[1];
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $updated_at_min = '2022-05-01T00:00:00-04:00';
                }
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2022-05-01T00:00:00-04:00';
            }
            $url = $url.'?created_at_min='.$updated_at_min;
        }
        if (!empty($type)) {
            $url = $url.'&limit='.$limit;
            $data = $this->geturl($url,$iscustom['shopifyapikey'],$iscustom['shopifysecretapikey']);
            $data = json_decode($data, true);
            $result = '';
            if (!empty($data['errors'])) {
                return '店铺已下线';
            }
            if (isset($data['customers'])) {
                if(is_array($data['customers']) && !empty($data['customers'])){
                    //方案1
                    $arr = array();
                    foreach ($data['customers'] as $k => $v) {
                        $arr['owner_id'] = 1;
                        $arr['is_published'] = 1;
                        $arr['modified_by'] = 1;
                        $arr['points'] = 0;
                        $arr['preferred_locale'] = 'zh_Hans_SG';
                        $arr['accounturl'] = $iscustom['id'];
                        $arr['customer_id'] = $v['id'];
                        $arr['ycreated_at'] = $v['created_at'];
                        $arr['date_identified'] = date('Y-m-d h:i:s', strtotime($v['updated_at']));
                        if (!empty($v['addresses'])) {
                            $arr['title'] = $v['addresses'][0]['name'];
                            $arr['firstname'] = $v['addresses'][0]['first_name'];
                            $arr['lastname'] = $v['addresses'][0]['last_name'];
                            $arr['company'] = $v['addresses'][0]['company'];
                            $arr['phone'] = $v['addresses'][0]['phone'];
                            $arr['address1'] = $v['addresses'][0]['address1'];
                            $arr['address2'] = $v['addresses'][0]['address2'];
                            $arr['city'] = $v['addresses'][0]['city'];
                            $arr['zipcode'] = $v['addresses'][0]['zip'];
                            $arr['country'] = $v['addresses'][0]['country'];
                        }
                        if (empty($arr['phone'])) {
                            $arr['phone'] = $v['phone'];
                        }
                        $arr['email'] = $v['email'];
                        $arr['mobile'] = $arr['phone'];
                        $arr['state'] = $v['state'];

                        $row = table('leads')
                            ->where('customer_id',$arr['customer_id'])
                            ->find();
                        if($row){
                            if($row['ycreated_at'] !== $arr['ycreated_at']){
                                $arr['date_modified'] = date('Y-m-d h:i:s', strtotime($v['updated_at']));
                                $result =  table('leads')->update($arr);
                            }else{
                                $result = $result.'重复';
                            }
                        }else{
                            $arr['date_added'] = date('Y-m-d h:i:s', strtotime($v['created_at']));
                            $result =  table('leads')->insert($arr);
                        }
                    }
                }else{
                    $result = $data;
                }
            }
        }
        return $result;
    }

    //http://zh.dnssystem.cn/api/Mautic/MauticShopifyCustomers
    //获取顾客订单
    public function MauticShopifyCustomers($id = null)
    {
        if (!empty($id)) {
            $leads =  Db::connect($this->connection)->name('leads')
                ->where('id',$id)
                ->select();
        }else {
            $ids = $this->request->request('ids');
            $where = array();
            if (!empty($ids)) {
                $where['accounturl'] = $ids;
            }else{
                //从56店铺开始更新
                $where['accounturl']  = array('egt',56);
            }
            $leads = Db::connect($this->connection)->name('leads')
                ->order('updatetime_mautic asc')
                ->where($where)
                ->limit('10')
                ->select();
        }
        if (!empty($leads)) {
            $row = array();
            $result = array();
            foreach ($leads as $t) {
                $iscustom = table('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                $url = $iscustom['shopifyname']."/admin/api/2021-07/customers/".$t['customer_id']."/orders.json";
                $data = $this->geturl($url,$iscustom['shopifyapikey'],$iscustom['shopifysecretapikey']);
                $data = json_decode($data, true);
                if (!empty($data['errors']) || !empty($data['error'])) {
                    $this->success('店铺已下线');
                }
                if (isset($data['orders'])) {
                    if(is_array($data['orders']) && !empty($data['orders'])){
                        //方案1
                        $arr = array();
                        foreach ($data['orders'] as $k => $v) {
                            $arr['accounturl'] = $t['accounturl'];
                            $arr['order_id'] = $v['id'];
                            $arr['customer_id'] = $t['customer_id'];

                            $row = Db::connect($this->connection)->name('leads_order')
                                ->where('order_id',$v['id'])
                                ->find();
                            if($row){
                                $result[] = '重复';
                            }else{
                                $result[] =  Db::connect($this->connection)->name('leads_order')->insert($arr);
                            }
                        }
                    }else{
                        $result[] = $data;
                    }
                }
                $row['updatetime_mautic'] = time();
                Db::connect($this->connection)->name('leads')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功',$result);
        } else {
            $this->error('未找到相关数据');
        }
    }

    //http://zh.dnssystem.cn/api/Mautic/testcustomers?id=5741965770825&accounturl=56
    //获取顾客信息
    public function testcustomers()
    {
        $id = $this->request->request('id');
        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        }
        $iscustom = table('fedition_accounturl')
            ->where($where)
            ->find();
        $url = $iscustom['shopifyname']."/admin/api/2021-07/customers/".$id.".json";
        $data = $this->geturl($url,$iscustom['shopifyapikey'],$iscustom['shopifysecretapikey']);
        $data = json_decode($data, true);
        dump($data);
        die;
    }

    //http://zh.dnssystem.cn/api/Mautic/testorder?id=5741965770825&accounturl=56
    //获取顾客订单信息
    public function testorder()
    {
        $id = $this->request->request('id');
        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        }
        $iscustom = table('fedition_accounturl')
            ->where($where)
            ->find();
        $url = $iscustom['shopifyname']."/admin/api/2021-07/customers/".$id."/orders.json";
        $data = $this->geturl($url,$iscustom['shopifyapikey'],$iscustom['shopifysecretapikey']);
        $data = json_decode($data, true);
        dump($data);
        die;
    }

    function geturl($url,$apikey,$secretapikey){
        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}
